<template>
  <div class="question-detail-page" v-loading="loading">
    <!-- 问题内容 -->
    <div v-if="questionDetail" class="question-content">
      <!-- 问题头部 -->
      <div class="question-header">
        <h1 class="question-title">{{ questionDetail.title }}</h1>

        <div class="question-meta">
          <div class="author-info" @click="goToProfile">
            <el-avatar
              :size="40"
              :src="getMediaUrl(questionDetail.author?.avatar)"
              class="author-avatar"
            >
              {{ questionDetail.author?.nickname?.charAt(0) || questionDetail.author?.username?.charAt(0) }}
            </el-avatar>
            <div class="author-details">
              <div class="author-name">
                {{ questionDetail.author?.nickname || questionDetail.author?.username }}
              </div>
              <div class="publish-info">
                <span>{{ formatTime(questionDetail.createdTime) }}</span>
                <span class="separator">·</span>
                <span>Raised a question</span>
              </div>
            </div>
          </div>

          <div class="question-actions">
            <el-dropdown trigger="click">
              <el-button type="text" class="more-btn">
                <el-icon><MoreFilled /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleEdit" v-if="canEdit">Editing issues</el-dropdown-item>
                  <el-dropdown-item @click="handleDelete" v-if="canEdit">Delete question</el-dropdown-item>
                  <el-dropdown-item @click="handleReport">Report</el-dropdown-item>
                  <el-dropdown-item @click="handleNotInterested">Not interested</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>

      <!-- 问题内容 -->
      <div v-if="questionDetail.content" class="question-body">
        <div class="question-content-text" v-html="formatContent(questionDetail.content)"></div>
      </div>

      <!-- 话题标签 -->
      <div v-if="questionDetail.topics && questionDetail.topics.length > 0" class="question-topics">
        <el-tag
          v-for="topic in questionDetail.topics"
          :key="topic.id"
          size="default"
          type="info"
          effect="plain"
          class="topic-tag"
          @click="goToTopic(topic.id)"
        >
          {{ topic.name }}
        </el-tag>
      </div>

      <!-- 问题统计和操作 -->
      <div class="question-footer">
        <div class="question-stats">
          <span class="stat-item">
            <el-icon><View /></el-icon>
            {{ formatCount(questionDetail.viewCount) }} browse
          </span>
          <span class="stat-item">
            <el-icon><ChatDotRound /></el-icon>
            {{ formatCount(questionDetail.answerCount) }} answer
          </span>
          <span class="stat-item">
            <el-icon><Star /></el-icon>
            {{ formatCount(questionDetail.followCount) }} follow
          </span>
        </div>

        <div class="question-operations">
          <!-- 关注按钮 -->
          <button
            class="operation-btn"
            :class="{ active: questionDetail.isFollowed }"
            @click="handleFollow"
          >
            <el-icon><Plus /></el-icon>
            <span>{{ questionDetail.isFollowed ? 'Followed' : 'Focus on issues' }}</span>
          </button>

          <!-- 点赞按钮 -->
          <button
            class="operation-btn"
            :class="{ active: questionDetail.isLiked }"
            @click="handleLike"
          >
            <el-icon><CaretTop /></el-icon>
            <span>{{ formatCount(questionDetail.likeCount) }}</span>
          </button>

          <!-- 分享按钮 -->
          <button
            class="operation-btn"
            @click="handleShare"
          >
            <el-icon><Share /></el-icon>
            <span>Share</span>
          </button>
        </div>
      </div>
    </div>

    <!-- 回答区域 -->
    <div class="answers-section">
      <!-- 写回答 -->
      <div class="write-answer">
        <el-button type="primary" @click="showAnswerEditor = !showAnswerEditor">
          <el-icon><EditPen /></el-icon>
          write an answer
        </el-button>
      </div>

      <!-- 回答编辑器 -->
      <div v-if="showAnswerEditor" class="answer-editor">
        <el-input
          v-model="answerContent"
          type="textarea"
          placeholder="Write your answer..."
          :rows="6"
          maxlength="10000"
          show-word-limit
        />
        <div class="editor-actions">
          <el-button @click="showAnswerEditor = false">Cancel</el-button>
          <el-button type="primary" @click="handleSubmitAnswer" :loading="submittingAnswer">
            Publish answer
          </el-button>
        </div>
      </div>

      <!-- 回答列表 -->
      <AnswerList
        ref="answerListRef"
        :question-id="questionDetail?.id"
        :question-author-id="questionDetail?.author?.userId"
        :refresh-trigger="refreshAnswerTrigger"
        @write-answer="showAnswerEditor = true"
        @answer-deleted="handleAnswerDeleted"
        @answer-updated="handleAnswerUpdated"
      />
    </div>
  </div>
</template>

<script setup>
import {computed, onMounted, ref} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {ElMessage, ElMessageBox} from 'element-plus'
import {useUserStore} from '@/stores/user'
import {
  deleteQuestion,
  getQuestionDetail,
  incrementViewCount,
  toggleFollowQuestion,
  toggleLikeQuestion
} from '@/api/question'
import {createAnswer} from '@/api/answer'
import {formatCount, formatTime} from '@/utils/format'
import {getMediaUrl} from '@/utils/media'
import AnswerList from '@/components/AnswerList.vue'
import {shareContent} from '@/utils/clipboard'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const questionDetail = ref(null)
const showAnswerEditor = ref(false)
const answerContent = ref('')
const submittingAnswer = ref(false)
const answerListRef = ref()
const refreshAnswerTrigger = ref(0)

// 计算属性
const canEdit = computed(() => {
  return userStore.userInfo?.userId === questionDetail.value?.author?.userId
})

// 获取问题详情
const fetchQuestionDetail = async () => {
  const questionId = route.params.id
  if (!questionId) {
    ElMessage.error('问题ID不能为空')
    return
  }

  loading.value = true
  try {
    const response = await getQuestionDetail(questionId)
    if (response.code === 200) {
      questionDetail.value = response.data

      // 增加浏览数
      incrementViewCount(questionId).catch(() => {
        // 静默处理浏览数增加失败
      })
    } else {
      ElMessage.error(response.message || '获取问题详情失败')
    }
  } catch (error) {
    console.error('获取问题详情失败:', error)
    ElMessage.error('获取问题详情失败')
  } finally {
    loading.value = false
  }
}

// 跳转到作者主页
const goToProfile = () => {
  if (questionDetail.value?.author?.userId) {
    router.push(`/people/${questionDetail.value.author.userId}`)
  }
}

// 跳转到话题页面
const goToTopic = (topicId) => {
  router.push(`/topic/${topicId}`)
}

// 处理关注
const handleFollow = async () => {
  try {
    const response = await toggleFollowQuestion(questionDetail.value.id)
    if (response.code === 200) {
      questionDetail.value.isFollowed = !questionDetail.value.isFollowed
      questionDetail.value.followCount += questionDetail.value.isFollowed ? 1 : -1
      ElMessage.success(questionDetail.value.isFollowed ? '关注成功' : '已取消关注')
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 处理点赞
const handleLike = async () => {
  try {
    const response = await toggleLikeQuestion(questionDetail.value.id)
    if (response.code === 200) {
      questionDetail.value.isLiked = !questionDetail.value.isLiked
      questionDetail.value.likeCount += questionDetail.value.isLiked ? 1 : -1
      ElMessage.success(questionDetail.value.isLiked ? '点赞成功' : '已取消点赞')
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 处理分享
const handleShare = async () => {
  try {
    const result = await shareContent({
      title: questionDetail.value.title,
      text: questionDetail.value.content || questionDetail.value.title,
      url: window.location.href
    })

    if (result.success && result.method === 'clipboard') {
      ElMessage.success('分享链接已复制到剪贴板')
    } else if (!result.success && result.reason !== 'cancelled') {
      ElMessage({
        message: `请手动复制链接：${window.location.href}`,
        type: 'info',
        duration: 10000,
        showClose: true
      })
    }
  } catch (error) {
    console.error('分享失败:', error)
    ElMessage.error('分享失败')
  }
}

// 处理编辑
const handleEdit = () => {
  // TODO: 跳转到编辑页面
  ElMessage.info('编辑功能开发中')
}

// 处理删除
const handleDelete = async () => {
  try {
    await ElMessageBox.confirm('确定要删除这个问题吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await deleteQuestion(questionDetail.value.id)
    if (response.code === 200) {
      ElMessage.success('问题已删除')
      router.push('/question')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 处理举报
const handleReport = () => {
  ElMessage.info('举报功能开发中')
}

// 处理不感兴趣
const handleNotInterested = () => {
  ElMessage.info('不感兴趣功能开发中')
}

// 格式化内容
const formatContent = (content) => {
  if (!content) return ''
  // 简单的换行处理
  return content.replace(/\n/g, '<br>')
}

// 处理回答删除
const handleAnswerDeleted = () => {
  // 更新问题的回答数
  if (questionDetail.value && questionDetail.value.answerCount > 0) {
    questionDetail.value.answerCount -= 1
  }
}

// 处理回答更新
const handleAnswerUpdated = () => {
  // 可以在这里处理回答更新后的逻辑
  console.log('回答已更新')
}

// 提交回答
const handleSubmitAnswer = async () => {
  if (!answerContent.value.trim()) {
    ElMessage.warning('请输入回答内容')
    return
  }

  if (!userStore.userInfo?.userId) {
    ElMessage.warning('请先登录')
    return
  }

  submittingAnswer.value = true
  try {
    const response = await createAnswer({
      questionId: questionDetail.value.id,
      content: answerContent.value,
      isAnonymous: false
    })

    if (response.code === 200) {
      ElMessage.success('回答发布成功')
      answerContent.value = ''
      showAnswerEditor.value = false
      // 更新问题的回答数
      if (questionDetail.value) {
        questionDetail.value.answerCount += 1
      }
      // 刷新回答列表
      refreshAnswerTrigger.value += 1
    } else {
      ElMessage.error(response.message || '发布回答失败')
    }
  } catch (error) {
    console.error('发布回答失败:', error)
    ElMessage.error('发布回答失败')
  } finally {
    submittingAnswer.value = false
  }
}

// 页面加载时获取数据
onMounted(async () => {
  await fetchQuestionDetail()

  // 处理hash定位到具体回答
  if (route.hash) {
    setTimeout(() => {
      const element = document.querySelector(route.hash)
      if (element) {
        element.scrollIntoView({
          behavior: 'smooth',
          block: 'center'
        })
        // 添加高亮效果
        element.classList.add('highlight-answer')
        setTimeout(() => {
          element.classList.remove('highlight-answer')
        }, 3000)
      }
    }, 500) // 等待回答列表加载完成
  }
})
</script>

<style lang="scss" scoped>
.question-detail-page {
  max-width: 800px;
  margin: 0 auto;
  padding: 0;
}

.question-content {
  background: $background-color;
  border-radius: $border-radius-large;
  padding: 40px;
  box-shadow: $shadow-light;
  margin-bottom: 32px;
}

.question-header {
  margin-bottom: 32px;
}

.question-title {
  font-size: 28px;
  font-weight: 600;
  color: $text-color;
  line-height: 1.4;
  margin: 0 0 24px 0;
}

.question-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 16px;
  cursor: pointer;
  flex: 1;
}

.author-details {
  flex: 1;
}

.author-name {
  font-size: 16px;
  font-weight: 500;
  color: $text-color;
  margin-bottom: 4px;
}

.publish-info {
  font-size: 14px;
  color: $text-secondary;

  .separator {
    margin: 0 8px;
  }
}

.more-btn {
  color: $text-light;
  padding: 8px;

  &:hover {
    color: $text-secondary;
    background-color: $background-light;
  }
}

.question-body {
  margin-bottom: 24px;
}

.question-content-text {
  font-size: 16px;
  line-height: 1.8;
  color: $text-color;
  word-wrap: break-word;
}

.question-topics {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 32px;
}

.topic-tag {
  font-size: 14px;
  cursor: pointer;

  &:hover {
    background-color: $primary-color;
    color: white;
    border-color: $primary-color;
  }
}

.question-footer {
  border-top: 1px solid $border-light;
  padding-top: 24px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.question-stats {
  display: flex;
  align-items: center;
  gap: 24px;
}

.stat-item {
  display: flex;
  align-items: center;
  // gap: 6px;
  font-size: 14px;
  color: $text-secondary;

  .el-icon {
    font-size: 16px;
  }
}

.question-operations {
  display: flex;
  align-items: center;
  gap: 16px;
}

.operation-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  background: none;
  border: 1px solid $border-color;
  color: $text-secondary;
  font-size: 14px;
  cursor: pointer;
  padding: 8px 16px;
  border-radius: $border-radius-medium;
  transition: all 0.2s ease;

  &:hover {
    color: $primary-color;
    border-color: $primary-color;
    background-color: rgba(0, 132, 255, 0.06);
  }

  &.active {
    color: $primary-color;
    border-color: $primary-color;
    background-color: rgba(0, 132, 255, 0.1);
  }

  .el-icon {
    font-size: 16px;
  }
}

.answers-section {
  background: $background-color;
  border-radius: $border-radius-large;
  padding: 32px;
  box-shadow: $shadow-light;
}

.answers-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid $border-light;
}

.answers-title {
  font-size: 20px;
  font-weight: 600;
  color: $text-color;
  margin: 0;
}

.write-answer {
  margin-bottom: 24px;
}

.answer-editor {
  background: $background-light;
  border-radius: $border-radius-medium;
  padding: 20px;
  margin-bottom: 24px;

  .editor-actions {
    margin-top: 16px;
    text-align: right;

    .el-button {
      margin-left: 12px;
    }
  }
}

.answers-list {
  min-height: 200px;
}

.empty-answers {
  text-align: center;
  padding: 40px 20px;
}

.answer-placeholder {
  text-align: center;
  padding: 40px 20px;
  color: $text-secondary;
}

// 回答高亮效果
:deep(.highlight-answer) {
  animation: highlightAnswer 3s ease-in-out;
  border: 2px solid #b92b27;
  border-radius: 8px;
}

@keyframes highlightAnswer {
  0% {
    background-color: rgba(22, 119, 255, 0.1);
    transform: scale(1.02);
  }
  50% {
    background-color: rgba(22, 119, 255, 0.05);
  }
  100% {
    background-color: transparent;
    transform: scale(1);
  }
}
</style>
